package ld.oauth.blog.service.user.impl;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import ld.oauth.blog.mapper.user.SysPermissionMapper;
import ld.oauth.blog.mapper.user.SysRoleMapper;
import ld.oauth.blog.model.po.user.SysPermission;
import ld.oauth.blog.model.po.user.SysRole;
import ld.oauth.blog.service.user.SysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author
 * @since 2022-09-03
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteById(Long id) {
        baseMapper.deleteById(id);
        baseMapper.deleteRolePermissionByRoleId(id);
        return true;
    }

    /**
     * 通过角色id查询角色和权限信息
     * @param id
     * @return
     */
    @Override
    public SysRole findById(Long id) {
        SysRole sysRole;
        if(id ==null){
            sysRole = new SysRole();
        }else {
            //1查询角色
             sysRole = baseMapper.selectById(id);
            //查询权限
            List<SysPermission> permissions = sysPermissionMapper.findByRoleId(id);
            //把权限设置到角色中
            sysRole.setPermissionList(permissions);
        }
        return sysRole;
    }

    @Override
    public IPage<SysRole> selectPage(Page<SysRole> page, SysRole sysRole) {
        return getBaseMapper().selectPage(page, sysRole);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveOrUpdate(SysRole entity) {
        entity.setUpdateDate(LocalDateTime.now());
        //更新角色
        boolean flag = super.saveOrUpdate(entity);

        if(flag){
            //更新权限(删除)
            baseMapper.deleteRolePermissionByRoleId(entity.getId());
            if(!CollectionUtils.isEmpty(entity.getPerIds())){
                baseMapper.saveRolePermission(entity.getId(),entity.getPerIds());
            }
        }
        return flag;
    }




}
